package com.virtualmall.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.virtualmall.bean.ShoppingCart;
import com.virtualmall.common.Page;
import com.virtualmall.dao.ShoppingCartDao;

@Repository
public class ShoppingCartDaoImpl extends GenericDaoHibernateImpl<ShoppingCart, Long> implements ShoppingCartDao {
	public ShoppingCartDaoImpl() {
		super(ShoppingCart.class);
	}

	@SuppressWarnings("unchecked")
	public List<ShoppingCart> getShoppingCartList(Long userId,Page page) {
		String hql = "select s.id as id,s.count as count,s.product as product " +
				"from ShoppingCart s where s.account.id = ? order by s.createDate desc";
		
        Query query = this.getCurrentSession().createQuery(hql)
                .setResultTransformer(Transformers.aliasToBean(ShoppingCart.class));
        query.setLong(0, userId);
        
        if (page != null) {
            query.setFirstResult((page.getCurrentPage() - 1)
                    * page.getPerPageSize());
            query.setMaxResults(page.getPerPageSize());
        }
        
		return (List<ShoppingCart>)query.list();
	}

	public Long getShoppingCartListCount(Long userId) {
		String hql = "select count(s.id) from ShoppingCart s where s.account.id = ?";
		
		Query query = this.getCurrentSession().createQuery(hql);
        query.setLong(0, userId);
		
		return (Long)query.uniqueResult();
	}

	@Override
	public void delete(Long userId) {
		String hql = "delete from ShoppingCart s where s.account.id = ?";
		
		Query query = this.getCurrentSession().createQuery(hql);
        query.setLong(0, userId);
		
		query.executeUpdate();
	}

    @Override
    public Double getShoppingCartTotalPrice(Long userId) {
        String hql = "select sum(s.count*s.product.discountPrice) from ShoppingCart s where s.account.id = ?";
        
        Query query = this.getCurrentSession().createQuery(hql);
        query.setLong(0, userId);
        
        return (Double)query.uniqueResult();
    }
}
